#!/bin/bash
#
# FFmpeg安装脚本 - Linux/macOS版本
#

echo "================================"
echo "   FFmpeg安装脚本"
echo "================================"
echo

# 检查是否已安装FFmpeg
if command -v ffmpeg >/dev/null 2>&1; then
    echo "FFmpeg已安装"
    ffmpeg -version
    exit 0
fi

# 检测操作系统
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "检测到Linux系统"
    
    # 检查包管理器
    if command -v apt-get >/dev/null 2>&1; then
        echo "使用apt安装FFmpeg..."
        sudo apt-get update
        sudo apt-get install -y ffmpeg
        
    elif command -v yum >/dev/null 2>&1; then
        echo "使用yum安装FFmpeg..."
        sudo yum install -y ffmpeg
        
    elif command -v dnf >/dev/null 2>&1; then
        echo "使用dnf安装FFmpeg..."
        sudo dnf install -y ffmpeg
        
    else
        echo "不支持的包管理器，尝试从源码编译..."
        install_from_source
    fi
    
elif [[ "$OSTYPE" == "darwin"* ]]; then
    echo "检测到macOS系统"
    
    # 检查是否已安装Homebrew
    if command -v brew >/dev/null 2>&1; then
        echo "使用Homebrew安装FFmpeg..."
        brew install ffmpeg
    else
        echo "请先安装Homebrew: https://brew.sh/"
        exit 1
    fi
    
else
    echo "不支持的平台: $OSTYPE"
    exit 1
fi

# 验证安装
if command -v ffmpeg >/dev/null 2>&1; then
    echo
    echo "================================"
    echo "   FFmpeg安装完成！"
    echo "================================"
    echo
    ffmpeg -version
    echo
    echo "安装成功！"
else
    echo "安装失败，请手动安装FFmpeg"
    exit 1
fi

install_from_source() {
    echo "从源码编译FFmpeg..."
    
    # 创建临时目录
    TEMP_DIR=$(mktemp -d)
    cd "$TEMP_DIR"
    
    # 下载FFmpeg源码
    echo "下载FFmpeg源码..."
    curl -L -o ffmpeg.tar.xz https://ffmpeg.org/releases/ffmpeg-5.1.tar.xz
    
    # 解压
    tar -xf ffmpeg.tar.xz
    cd ffmpeg-*
    
    # 配置和编译
    echo "配置FFmpeg..."
    ./configure --enable-shared --enable-pthreads --enable-gpl --enable-libx264
    
    echo "编译FFmpeg..."
    make -j$(nproc)
    
    echo "安装FFmpeg..."
    sudo make install
    
    # 清理临时文件
    cd /
    rm -rf "$TEMP_DIR"
    
    # 更新动态库缓存
    sudo ldconfig
}